<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 救火队队长
// +----------------------------------------------------------------------

namespace  app\cardeadmin\controller;

use app\api\controller\EmailSend;
use app\BaseController;
use app\common\model\Manage as ManageModule;
use app\common\model\ManageLog;
use app\common\model\UserLog;
use think\facade\Db;
use think\facade\View;
use think\facade\Session;

/**
 * 登陆管理
 * Class Login
 * @package app\admin\controller
 */
class Login extends  BaseController {

    /**
     * 登陆页
     * @author 救火队队长
     */
    public function  login() {
		if (Session('?manager')) {
            return redirect(url('Index/index'));
        }
        return View::fetch();
    }

    /**
     * 判断是否登陆
     * @author 救火队队长
     */
    public function checkLogin(){
        $data        = input('param.');
        $username    = trim($data['username']);
        $vercode     = trim($data['vercode'] ?? '');

        $userInfo    = Db::name('manage')->where(array('username' => $username))->find();
        if($userInfo){
            $mysql_email = $userInfo['email'];
            $mysql_ip    = $userInfo['ips'];

            if(empty($mysql_ip)){
                if(empty($vercode)){
                    return show(2,'',[]);
                }
                $current_manage_code = session("manage_{$mysql_email}");
                if($current_manage_code != $vercode){
                    return show(-1,'The email verification code is incorrect',[]);
                }
            }else{
                $is_email_check = getSetting('is_email_check');
                if($is_email_check != 1){
                    $ip_array  = explode(',',$mysql_ip);
                    if(!in_array(ip() , $ip_array)){
                        if(empty($vercode)){
                            return show(2,'',[]);
                        }
                        $current_manage_code = session("manage_{$mysql_email}");
                        if($current_manage_code != $vercode){
                            return show(-1,'The email verification code is incorrect',[]);
                        }
                    }
                }
            }
            $manageModel = new ManageModule();
            $result = $manageModel->toLogin($data);

            if($result['status']){
                $url = url("index/index");

                $datas = [
                    'href' =>  $url->build(),
                ];
                return show(0,"",$datas);
            }
            return show(-1,$result['msg'],[]);
        }else{
            $userLogModel = new ManageLog();
            $userLogModel->saveManageLog([
                'manage_id' => 0,
                'desc'      => 'manage login Error',
                'content'   => "'{$username}' login"
            ]);
            return show(-1,'account no found',[]);
        }
    }

    public function emailSend()
    {
        $username    = input('post.username' , '','trim');
        $email       = Db::name('manage')->where(['username'=>trim($username)])->value('email');
        if(empty($email)) return json(['code'=>0,'msg'=>"account no found"]);

        $current_manage_code_time   = \session("manage_{$email}_time");
        $current_time               = getUtcTime();

        if($current_time - $current_manage_code_time < 60){
            return json(['code'=>0,'msg'=>"The verification code is valid for 1 minutes, please check your email."]);
        }

        //获取随机6位字母
        $round_num     = nonceStr();
        $result         =  EmailSend::sendGridEmail('manage_email_check' , [
            'email'     => $email,
            'code'      => $round_num
        ]);
        if($result){
            \session("manage_{$email}", $round_num);
            \session("manage_{$email}_time", $current_time);
            return json(['code'=>1,'msg'=>"Email verification code has been sent."]);
        }else{
            return json(['code'=>0,'msg'=>"Send mail failed!"]);
        }
    }

    /**
     * 用户退出
     * @author 救火队队长
     */
    public function logout()
    {
        //增加退出日志
        if(session('manage.id')){
            $userLogModel = new ManageLog();
            $userLogModel->saveManageLog([
                'manage_id' => session('manage.id'),
                'desc'      => 'manage logout',
                'content'   => ''
            ]);
        }
        Session('manage', null);
        return redirect(url('login/login'));
    }





}
